<template>
  <el-dialog
    v-model="visible"
    title="签到详情"
    width="80%"
    :before-close="close"
    destroy-on-close
  >
    <div class="attendance-calendar">
      <el-calendar 
        v-model="currentDate" 
        @update:current-date="handleMonthChange"
      >
        <template #date-cell="{ data }">
          <el-tooltip
            :disabled="isFutureDate(data.date)"
            :content="getTooltipContent(data)"
            placement="top"
            popper-class="attendance-tooltip"
            raw-content
          >
            <div class="calendar-day">
              <div class="day-number">{{ data.day.split('-')[2] }}</div>
              
              <!-- 状态标签 -->
              <div 
                v-if="showStatus(data)"
                :class="['status-label', getStatusClass(data)]"
              >
                {{ getStatusText(data) }}
              </div>
            </div>
          </el-tooltip>
        </template>
      </el-calendar>
    </div>
    
    <!-- 关闭按钮 -->
    <div class="close-button">
      <el-button type="primary" @click="close">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import req from '@/request'

const visible = ref(false)
const signTypeOptions = [
  { value: 1, label: '正常' },
  { value: 2, label: '未签到' },
  { value: 3, label: '未签退' },
  { value: 4, label: '异常' }
]

const SignList = ref([])
const overview = ref({})
const yearMoth = ref('')
const currentDate = ref(new Date())

const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const attendanceMap = computed(() => {
  return SignList.value.reduce((map, item) => {
    map[item.date] = item
    return map
  }, {})
})

const isHoliday = (date) => {
  const day = date.getDay()
  return day === 0 || day === 6
}

const isFutureDate = (date) => {
  return new Date(formatDate(date)) > new Date()
}

const showStatus = (data) => {
  const dateStr = formatDate(data.date)
  return !isFutureDate(data.date) && !isHoliday(data.date)
}

const getStatusClass = (data) => {
  const dateStr = formatDate(data.date)
  const record = attendanceMap.value[dateStr]
  
  if (!record) return 'abnormal'
  
  switch(record.status) {
    case 1: return 'normal'
    case 2: return 'no-signin'
    case 3: return 'no-signout'
    default: return 'abnormal'
  }
}

const getStatusText = (data) => {
  const dateStr = formatDate(data.date)
  const record = attendanceMap.value[dateStr]
  
  if (!record) return signTypeOptions.find(opt => opt.value === 4)?.label
  return signTypeOptions.find(opt => opt.value === record.status)?.label
}

const getTooltipContent = (data) => {
  const dateStr = formatDate(data.date)
  const record = attendanceMap.value[dateStr]
  
  if (isHoliday(data.date)) {
    return `
      <div class="holiday-tip">
        <i class="el-icon-date"></i>
        <span>节假日</span>
        <div class="holiday-desc">无考勤要求</div>
      </div>
    `
  }
  
  const statusText = record ? signTypeOptions.find(opt => opt.value === record.status)?.label : '异常'
  const signIn = record?.signInTime ? `<span class="time">${record.signInTime}</span>` : '<span class="absent">未签到</span>'
  const signOut = record?.signOutTime ? `<span class="time">${record.signOutTime}</span>` : '<span class="absent">未签退</span>'
  
  return `
    <div class="tooltip-content">
      <div class="tip-header">
        <span class="date">${dateStr}</span>
        <span class="status ${getStatusClass(data)}">${statusText}</span>
      </div>
      <div class="tip-item">
        <span class="label">签到：</span>
        ${signIn}
      </div>
      <div class="tip-item">
        <span class="label">签退：</span>
        ${signOut}
      </div>
    </div>
  `
}

const getSignList = async () => {
  try {
    const params = {
      userId: overview.value.userId,
      month: yearMoth.value
    }
    const res = await req.get('/clockLogs/listByUserId', { params })
    SignList.value = res.data || []
    console.log("获取考勤：", SignList.value)
  } catch (error) {
    console.error('获取考勤数据失败', error)
    ElMessage.error('获取考勤记录失败')
  }
}

const open = async (Data, _yearMoth) => {
  visible.value = true
  overview.value = Data
  yearMoth.value = _yearMoth
  currentDate.value = new Date(_yearMoth.replace(/-/g, '/') + '/01')
  console.log("数据：", overview.value)
  console.log("月份", yearMoth.value)
  await getSignList()
}

const close = () => {
  visible.value = false
}

// 处理月份变化
const handleMonthChange = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  yearMoth.value = `${year}-${month}`
  
  getSignList()
  console.log("重新调用：", yearMoth.value)
}

// 监听yearMoth变化，同步到currentDate
watch(yearMoth, (newVal) => {
  if (newVal) {
    const [year, month] = newVal.split('-')
    currentDate.value = new Date(`${year}/${month}/01`)
  }
}, { immediate: true })

// 初始化时同步currentDate和yearMoth
watch(currentDate, (newVal) => {
  if (newVal) {
    const year = newVal.getFullYear()
    const month = String(newVal.getMonth() + 1).padStart(2, '0')
    yearMoth.value = `${year}-${month}`
  }
})

defineExpose({
  open,
  close
})
</script>

<style scoped>
.attendance-calendar {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.calendar-day {
  position: relative;
  height: 100%;
  padding: 8px;
  text-align: center;
}

.day-number {
  font-size: 14px;
  margin-bottom: 4px;
}

.status-label {
  font-size: 12px;
  padding: 2px 4px;
  border-radius: 4px;
  margin-top: 2px;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 90%;
}

.status-label.normal {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-label.no-signin {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-label.no-signout {
  background-color: #ecf5ff;
  color: #409eff;
}

.status-label.abnormal {
  background-color: #fef0f0;
  color: #f56c6c;
}
</style>

<style>
.attendance-tooltip {
  background: #ffffff!important;
  border: 1px solid #ebeef5!important;
  border-radius: 8px!important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15)!important;
  padding: 12px!important;
  font-size: 13px!important;
  line-height: 1.6!important;
  max-width: 220px!important;
}

.attendance-tooltip .holiday-tip {
  text-align: center;
  color: #f56c6c;
}

.attendance-tooltip .holiday-tip i {
  font-size: 24px;
  display: block;
  margin-bottom: 6px;
}

.attendance-tooltip .holiday-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.attendance-tooltip .tip-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #ebeef5;
}

.attendance-tooltip .date {
  font-weight: bold;
  color: #303133;
}

.attendance-tooltip .status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.attendance-tooltip .status.normal {
  background-color: #f0f9eb;
  color: #67c23a;
}

.attendance-tooltip .status.no-signin {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.attendance-tooltip .status.no-signout {
  background-color: #ecf5ff;
  color: #409eff;
}

.attendance-tooltip .status.abnormal {
  background-color: #fef0f0;
  color: #f56c6c;
}

.attendance-tooltip .time {
  color: #606266;
}

.attendance-tooltip .tip-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 6px 0;
}

.attendance-tooltip .label {
  color: #909399;
  margin-right: 12px;
}

.attendance-tooltip .absent {
  color: #f56c6c;
  font-weight: 500;
}
</style>